package com.qen.common;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author licz
 * @data 2025年05月15日 10:24 AM
 */
public class GenericTypeUtils {

    /**
     * 默认就取第一个泛型类型
     *
     * @param genericSuperclass
     * @param <T>
     * @return
     */
    public static <T> Class<T> getGenericType(Type genericSuperclass) {
        if (genericSuperclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments.length > 0 && actualTypeArguments[0] instanceof Class<?>) {
                return (Class<T>) actualTypeArguments[0];
            }
        }
        throw new IllegalArgumentException("无法确定泛型类型");
    }

    /**
     * 取第几个泛型类型
     *
     * @param genericSuperclass
     * @param no
     * @param <T>
     * @return
     */
    public static <T> Class<T> getGenericType(Type genericSuperclass, int no) {
        if (genericSuperclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments.length > 0 && actualTypeArguments[no] instanceof Class<?>) {
                return (Class<T>) actualTypeArguments[no];
            }
        }
        throw new IllegalArgumentException("无法确定泛型类型");
    }

}
